from django.shortcuts import render
from rest_framework import filters
from rest_framework.generics import GenericAPIView, ListAPIView
from .models import SKU
from rest_framework.response import Response
from . import serializers
from .serializers import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet


class HotSkuListView(ListAPIView):
    serializer_class = serializers.HoSkuListSerializer
    pagination_class = None  # 因为分页在全局配置的 所以这里需要关闭分页能显示热门商品

    def get_queryset(self):
        category_id = self.kwargs.get("category_id")  # 获得分类ID
        skus = SKU.objects.filter(category_id=category_id).order_by("-sales")[:4]
        # 获取到商品数据后按照销量排行

        return skus

    # def get(self, request, category_id):
    #     # 获取对象  获取销量排行的数据
    #     queryset = self.get_queryset()
    #     # 获取序列化器
    #     serializer = self.get_serializer(instance=queryset, many=True)
    #
    #     # 返回数据
    #     return Response(serializer.data)

class SkuListView(ListAPIView):
    serializer_class = serializers.HoSkuListSerializer
    # 给热门商品序列化器补充一个comments字段然后直接可以直接使用

    # 设置过滤后端,排序字段
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):  # 数据集
        # 获取分类编号
        category_id = self.kwargs.get("category_id")
        # 根据分类编号查询数据
        skus = SKU.objects.filter(category_id=category_id)

        # 返回数据
        return skus

# 搜索视图
class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    # 数据集
    index_models = [SKU]

    # 序列化器
    serializer_class = SKUIndexSerializer